import {
  Cartesian3,
  Camera as CesiumCamera,
  KmlDataSource as CesiumKmlDataSource,
  Math as CesiumMath,
  Scene as CesiumScene,
  Viewer as CesiumViewer,
  Color,
  ColorMaterialProperty,
  ConstantProperty,
  Ellipsoid,
  Entity,
  JulianDate,
  PolygonHierarchy,
  Rectangle,
} from 'cesium'
import 'cesium/Build/Cesium/Widgets/widgets.css'
import { Camera, CesiumComponentRef, CesiumMovementEvent, KmlDataSource, Scene, Viewer } from 'resium'

const time = new JulianDate()
const rect = new Rectangle()
const tempRect = new Rectangle()

type LabelItem = { position: Cartesian3; text: string }
const colors = [0xffc06b5c, 0xff5053ef, 0xff6b7900, 0xff3c8e38, 0xff2dc0fb, 0xfff4a522, 0xffbc47ab, 0xffff0000]
// const colors = [0xc06b5c, 0x5053ef, 0x6b7900, 0x3c8e38, 0x2dc0fb, 0xf4a522, 0xbc47ab, 0xffff0000]

export default function CesiumMap() {
  const cameraRef = useRef<CesiumComponentRef<CesiumCamera>>(null)
  const viewerRef = useRef<CesiumComponentRef<CesiumViewer>>(null)
  const sceneRef = useRef<CesiumComponentRef<CesiumScene>>(null)
  const [labels, setLabels] = useState<LabelItem[]>([])
  function onKmlLoad(datasource: CesiumKmlDataSource) {
    console.log('datasource', datasource)
    // const viewer = viewerRef.current!.cesiumElement!
    // viewer.imageryLayers.removeAll()
    // viewer.scene.globe.baseColor = Color.fromBytes(12, 74, 136)
    // viewer.scene.skyAtmosphere.show = false
    // var scene = viewer.scene
    // var cameraController = scene.screenSpaceCameraController
    // cameraController.minimumZoomDistance = 80000
    // cameraController.maximumZoomDistance = 150000

    const arr = datasource.entities.values
    const extrudedHeightProperty = new ConstantProperty(1000)
    const closeTop = new ConstantProperty(true)
    const labelArr = [] as LabelItem[]
    arr.forEach((e, idx) => {
      if (!e.polygon) return
      e.polygon.extrudedHeight = extrudedHeightProperty
      const materialProperty = new ColorMaterialProperty(Color.fromRgba(colors[idx % colors.length]))
      // const materialProperty = new ColorMaterialProperty(Color.fromRandom({ minimumAlpha: 1 }))
      e.polygon.material = materialProperty
      e.polygon.outline = undefined
      e.polygon.outlineColor = undefined
      e.polygon.closeTop = closeTop
      e.polygon.closeBottom = closeTop
      console.log('e', e.name)
      const polygon = e.polygon.hierarchy!.getValue(time) as PolygonHierarchy
      const pArr = polygon.positions
      Rectangle.fromCartesianArray(pArr, Ellipsoid.WGS84, tempRect)
      if (rect.west === 0) tempRect.clone(rect)
      Rectangle.union(rect, tempRect, rect)
      const c1 = Rectangle.center(tempRect)
      c1.height = extrudedHeightProperty.getValue(time) + 2000
      const position = Ellipsoid.WGS84.cartographicToCartesian(c1)
      // console.log('position', position, c1)
      const text = e.name || `区域${idx + 1}`
      labelArr.push({ text, position })
    })
    const c = cameraRef.current?.cesiumElement!
    const center = Cartesian3.fromDegrees(130.3, 43.6, 120000)
    c.setView({ destination: center, orientation: { heading: 0, pitch: -CesiumMath.PI_OVER_TWO * 0.6 } })
    setLabels(labelArr)
  }
  const [init, setInit] = useState(false)
  useEffect(() => {
    setTimeout(() => setInit(true), 1000)
  }, [])
  useEffect(() => {
    if (!labels.length) return
    const entities = viewerRef.current?.cesiumElement?.entities
    if (!entities) return
    labels.forEach(({ text, position }) => {
      entities.add({
        label: {
          text,
          font: '16px sans-serif',
          fillColor: Color.WHITE,
        },
        position,
      })
    })
  }, [viewerRef.current, labels])
  function onKmlClick(movement: CesiumMovementEvent, target: any) {
    console.log('movement', movement, target.id)
    const e = target.id as Entity
    alert(e.name)
  }
  if (!init) return null
  return (
    <Viewer
      ref={viewerRef}
      full
      terrainProvider={undefined}
      baseLayerPicker={false}
      fullscreenButton={false}
      homeButton={false}
      infoBox={false}
      timeline={false}
      geocoder={false}
      animation={false}
      selectionIndicator={false}
      navigationHelpButton={false}
      navigationInstructionsInitiallyVisible={false}
      sceneModePicker={false}
      vrButton={false}>
      {/* <ImageryLayer imageryProvider={imageryProvider} /> */}
      <Camera ref={cameraRef} />
      <Scene ref={sceneRef} />
      <KmlDataSource data={'/ml2.kml'} onLoad={onKmlLoad} onClick={onKmlClick} />
    </Viewer>
  )
}
